<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" prop="id" align="center" width="65" />
      <el-table-column label="广告位名称" prop="adName" align="center" />
      <el-table-column label="广告位图片" prop="adImg" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.adImg" width="100" alt="">
        </template>
      </el-table-column>
      <el-table-column label="广告位描述" prop="adDesc" align="center" />
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item :label-width="formLabelWidth" label="广告名称">
          <el-input v-model="temp.adName" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="广告描述">
          <el-input v-model="temp.adDesc" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="广告图片">
          <el-upload :on-preview="handlePreview" :on-remove="handleRemove" :file-list="temp.fileList" :action="host+'/admin/img/0'" :headers="headers" :limit="1" :on-success="handleSuccess" class="upload-demo" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

	<script>
import {
	fetchAdsAjax,
	addAdsAjax,
	updateAdsAjax,
	delAdsAjax
	// fetchRoleAjax
} from "@/api/ads";
import waves from "@/directive/waves"; // Waves directive
// import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

export default {
	name: "Ads",
	components: { Pagination },
	directives: { waves },
	filters: {},

	data() {
		return {
			tableKey: 0,
			list: [],
			total: 0,
			listLoading: true,
			listQuery: {
				pageNum: 1,
				pageSize: 10
			},
			textMap: {
				create: "新增广告",
				detail: "广告详情"
			},
			downloadLoading: false,
			dialogFormVisible: false,
			temp: {},
			formLabelWidth: "150px",
			rules: {},
			dialogStatus: "",
			tempList: [],
			headers: { Authorization: 'Bearer ' + this.$store.state.user.token },
			host: process.env.BASE_API
		};
	},
	computed: {
		adInfo() {
			return { adName: this.temp.adName, adDesc: this.temp.adDesc };
		}
	},
	created() {
		this.getList();
	},
	methods: {
		handleSuccess(file, fileList) {
			this.temp.fileList = [];
			this.temp.fileList.push({
				name: fileList.name,
				url: file.data.file
			})
		},
		handleRemove(file, fileList) {
			console.log(file, fileList);
		},
		handlePreview(file) {
			console.log(file);
		},
		getList() {
			this.listLoading = true;
			this.listLoading = false;
			this.listLoading = true;
			fetchAdsAjax(this.listQuery).then(response => {
				// if (respons.data.data.) {

				// }
				this.list = response.data.data.pageData;
				this.total = response.data.data.maxCount;
				this.listLoading = false;
			});
		},

		handleFilter() {
			this.listQuery.page = 1;
			this.getList();
		},

		handleCreate() {
			this.temp = {};
			this.dialogStatus = "create";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].resetFields();
			});
		},

		createData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					const formData = new FormData();
					formData.append("adName", this.temp.adName); // 这就是给formData添加新的表单数据的形式
					formData.append("adDesc", this.temp.adDesc);
					formData.append("adImg", this.temp.fileList[0].url);
					addAdsAjax(formData).then(() => {
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "创建成功",
							type: "success",
							duration: 2000
						});
						this.getList();
					});
				}
			});
		},
		handleUpdate(row) {
			row.fileList = [{
				name: row.adName,
				url: row.adImg
			}]
			this.temp = Object.assign({}, row); // copy obj
			this.dialogStatus = "update";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
		},
		updateData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					this.temp.adImg = this.temp.fileList[0].url;
					const tempData = Object.assign({}, this.temp);
					updateAdsAjax(tempData).then(() => {
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "更新成功",
							type: "success",
							duration: 2000
						});
						this.getList();
					});
				}
			});
		},
		handleDelete(row) {
			this.$confirm("确认删除该条数据吗?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				delAdsAjax(row).then(res => {
					// const index = this.list.indexOf(row);
					// this.list.splice(index, 1);
					if (res.data.code !== 0 || res.data.data.length < 0) {
						this.$message({
							message: "删除失败",
							type: "error",
							duration: 5 * 1000
						});
						return;
					}
					this.$notify({
						title: "成功",
						message: "删除成功",
						type: "success",
						duration: 2000
					});
					this.getList();
				});
			});
		}
	}
};
</script>
